package com.nettywork.hearbeat;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

    int overtimeNum = 0;

    /**
     * 心跳连接 超时之后调用
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent idleStateEvent =  (IdleStateEvent)evt;
        String hearbeatType = null;
        switch(idleStateEvent.state()){
            case READER_IDLE:
                hearbeatType = "读取客户端数据超时";
                overtimeNum++;
                break;
            case WRITER_IDLE:
                hearbeatType = "写入客户端数据超时";
                overtimeNum++;
                break;
            case ALL_IDLE:
                hearbeatType = "读写超时";
                overtimeNum++;
                break;
            default:
                break;
        }
        System.out.println(ctx.channel().remoteAddress() + ": 客户端超时次数,"+ overtimeNum + hearbeatType);
        if(overtimeNum >= 3){
            System.out.println("读空闲超过3次，关闭并释放连接");
            ByteBuf byteBuf = Unpooled.copiedBuffer("idle close".getBytes(CharsetUtil.UTF_8));
            ctx.writeAndFlush(byteBuf);
            ctx.channel().close();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf)msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        System.out.println(new String(bytes));
    }
}
